var app, path, loc;

loc = location.href.toString();
if (loc.charAt( loc.length-1 ) == '#') {
	location.href = loc.substr(0, loc.length-1);
} 

var delegate = function( obj, fn ) {
	return function() { return fn.apply(obj, arguments); }
}

$(document).ready(function() {
	
	var apps = [
   	   ['Shift Belle Nuit timecodes', './apps/bn-shifter'],
  	   ['Shift SRT timecodes', './apps/srt-shifter'],
	   ['Merge EDL timecodes into Belle Nuit', './apps/merger'],
	   ['Compare Belle Nuit files', './apps/compare'],
	   ['Multi-language SRT', './apps/linefilter'],
	   ['Fix Arabic SRT', './apps/arab-srt'],
	   ['SRT Editor', './apps/editor']
	];

	/**
	 * Checks whether a tool path is present in the current location.
	 * @param tool_path The path to a specific tool.
	 * @return True if the tool path is in the current location, false otherwise.
	 */
	var isCurrentTool = function(tool_path) {
		var path = tool_path.replace('.','');
		var loc = location.href.toString();
		loc = loc.replace('#', ''); 
		if( (loc.substr(loc.length-path.length, loc.length) == path) || (loc.substr(loc.length-path.length-1, loc.length) == path+'/')  ) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * Gives a path to prepend css files and images.
	 * @return '../../' if the current location contains a tool path, './' otherwise
	 */
	path = function() {
		var result = './';
		$(apps).each(function(i) {
			if ( isCurrentTool(apps[i][1]) ) {
				result = '../../';
			}
		});
		return result;
	}
	

	/**
	 * Checks whether the current location is a tool location.
	 * @return True if the current location belongs to a tool, false otherwise.
	 */
	var isToolLocation = function() {
		return path() == '../../';
	}
	

	// 
	
	//----------------------------------------------------------
	// 
	// LOAD CSS
	//
	//----------------------------------------------------------
	
	$("head").append("<link>");
	var css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: path() + "css/toolbar.css"
    });

	//----------------------------------------------------------
	// 
	// CREATE TOOLBAR
	//
	//----------------------------------------------------------
	
    // toolbar container
    var bar = $('<div>')
		.prependTo(document.body)
		.attr('id', 'bar')
		.attr('class', 'toolbar');
    
	var bar_content = $('<div>')
		.attr('class', 'bar-content')
		.appendTo(bar);
	
    // label: logo and title
	var label = $('<label>')
		.appendTo(bar_content)
		.click(function() {
			location.href = path();
		});
	
	// mindpirates skull logo
	var logo = $('<div>')
		.attr('class', 'logo')
		.appendTo(label);
	
	// title
	var title = $('<span>')
		.text('SUBTITLE TOOLS')
		.appendTo(label);
	
	// container for div.buttons
	var btn_c = $('<div>')
		.attr('class', 'buttons-container')
		.appendTo(bar_content);
	
	// div.buttons - holds styled buttons
	var buttons = $('<div>')
		.attr('class', 'buttons')
		.appendTo(btn_c);
	 
	// a button for each tool
	$(apps).each(function(i,t) {
		var tool_name = t[0];
		var tool_path = t[1];
		// link anchor
		var a = $('<a>')
			.attr('class', 'button')
			.attr('href', path() + tool_path)
			.click(function(e) {
				if ($(this).hasClass('active')) {
					e.preventDefault();
					return false;
				}
				location.href = path() + tool_path;
			})
			.appendTo(buttons);
	
		// link text
		var span = $('<span>')
			.text(tool_name)
			.appendTo(a); 
		if (isCurrentTool(tool_path)) {
			a.addClass('active');
		}
	});
	

	$('.clear-textarea').click(function(e) {
		e.stopPropagation(); 
		$(this).closest('.panel').find('textarea').val('');
		$(this).closest('.panel').find('textarea').trigger('clear')
		return false;
	}); 
	
	$('.description .content').css({
		width: $('.description .content').textWidth(),
		margin: '0 auto'
	});
	$('.description .content').hide();
	$('.description h4').click(function() {$('.description .content').toggle()});
});

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>'
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};


var loadFancybox = function(callback) {
	var script_path = path()+'js/jquery.fancybox-1.3.4/fancybox/';
	// css
	$("head").append("<link>");
	var css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: script_path + "jquery.fancybox-1.3.4.css"
    });
    // js
	jQuery.getScript(script_path+'jquery.easing-1.3.pack.js', function() {
		jQuery.getScript(script_path+'jquery.mousewheel-3.0.4.pack.js', function() {
			jQuery.getScript(script_path+'jquery.fancybox-1.3.4.pack.js', callback);
		});
	}); 
}

var TimeUtils = {
	stringToTime: function(string) {
		var hh,mm,ss,ms;
		var a = arguments;
		var p = a.length == 1 ? string.split(':') : null;
		hh = p ? Number(p[0]) : a[0];
		mm = p ? Number(p[1]) : a[1];
		ss = p ? Number(p[2]) : a[2];
		ms = p ? Number(p[3]) : a[3]; 
		return hh*60*60*1000 + mm*60*1000 + ss*1000	+ ms;
	},
	srtStringToTime: function(string) {
		var hh,mm,ss,ms;
		var a = arguments;
		var p = a.length == 1 ? string.split(':') : null;
		hh = p ? Number(p[0]) : a[0];
		mm = p ? Number(p[1]) : a[1];
		ss = p ? Number(p[2]) : a[2];
		ms = p ? Number(p[3]) : a[3]; 
		return hh*60*60*1000 + mm*60*1000 + ss*1000	+ ms;
	},
	timeToString: function(ms, twoDigitMs) { 

		var two = function(x) {return ((x>9)?"":"0")+x}
		var three = function(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}
		
		var sec = Math.floor(ms/1000)
		ms = ms % 1000;
		if (twoDigitMs && String(ms).length>2) {
			ms = Number(String(ms).substr(0,2));
		}
		t = two(ms);
		var min = Math.floor(sec/60)
		sec = sec % 60
		t = two(sec) + ":" + t

		var hr = Math.floor(min/60)
		min = min % 60
		t = two(min) + ":" + t

		//var day = Math.floor(hr/60)
		hr = hr % 60
		t = two(hr) + ":" + t
		//t = day + ":" + t

		return t
	}
}
   

jQuery.fn.extend({ 
    disableSelection : function() { 
            return this.each(function() { 
                    this.onselectstart = function() { return false; }; 
                    this.unselectable = "on"; 
                    jQuery(this).css('user-select', 'none'); 
                    jQuery(this).css('-o-user-select', 'none'); 
                    jQuery(this).css('-moz-user-select', 'none'); 
                    jQuery(this).css('-khtml-user-select', 'none'); 
                    jQuery(this).css('-webkit-user-select', 'none'); 
            }); 
    } 
}); 


function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/urlencode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();
 
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}